package net.j4love.websocket.spring.quickstart;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author he peng
 * @create 2017/9/8 17:20
 * @see
 */
public class MyWebSocketHandler extends TextWebSocketHandler {

    private static final Logger LOG = LoggerFactory.getLogger(MyWebSocketHandler.class);

    private Map<String , WebSocketSession> webSocketSessionMap = new ConcurrentHashMap<>();

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        if (LOG.isInfoEnabled()) {
            LOG.info("sessionId ==> {} URI ==> {} HandshakeHeaders ==> {} Principal ==> {} " +
                    "LocalAddress ==> {} RemoteAddress ==> {} " ,
                    session.getId() , session.getUri() , session.getHandshakeHeaders() ,
                    session.getPrincipal() , session.getLocalAddress() , session.getRemoteAddress());
        }
        webSocketSessionMap.put(session.getId() , session);
        super.handleTextMessage(session, message);
        ChatMessage chatMessage = JSON.parseObject(message.getPayload(), ChatMessage.class);
        chatMessage.setSendTime(DateFormatUtils.format(System.currentTimeMillis() , "yyyy-MM-dd HH:mm:ss"));
        TextMessage returnMessage = new TextMessage(JSON.toJSONString(chatMessage));
        for (Map.Entry<String, WebSocketSession> stringWebSocketSessionEntry : webSocketSessionMap.entrySet()) {
            WebSocketSession webSocketSession = stringWebSocketSessionEntry.getValue();
            if (webSocketSession.isOpen()) {
                webSocketSession.sendMessage(returnMessage);
            }
        }
    }
}
